<?php

namespace App\Http\Controllers;

use App\Http\Requests\LoginRequest;
use App\Http\Resources\UserShowResource;

class AuthController extends Controller
{
    public function login(LoginRequest $request)
    {
        $credentials = $request->only('username', 'password', 'phone');

        if ($token = $this->guard()->attempt($credentials)) {
            return $this->respondWithToken($token);
        }

        return $this->responseError('用户名 或 密码 错误', 401);
    }

    public function me()
    {
        $user             = $this->getUser();
        $user->permission = $user->getAllPermissions();
        return new UserShowResource($user);
    }

    public function logout()
    {
        $this->guard()->logout();
        return $this->responseSuccess(['message' => 'successfully logged out'], 204);
    }

    public function refresh()
    {
        $guard = $this->guard();
        if (!$guard->user()) {
            return $this->responseError('TOKEN 失效');
        }

        return $this->respondWithToken($guard->refresh());
    }
}
